package com.my.web.dao.impl;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.my.web.dao.IBaseDao;

@Repository("baseDao")
public class BaseDaoImpl<T> implements IBaseDao<T> {

	private SessionFactory sessionFactory;

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@Override
	public Serializable save(T entity) {
		Session session = this.sessionFactory.getCurrentSession();
		Serializable obj = session.save(entity);
		session.flush();
		return obj;
	}

	@Override
	public T get(String hql, Map<String, Object> params) {
		Session session = this.sessionFactory.getCurrentSession();
		Query qr = session.createQuery(hql);
		if (params != null && !params.isEmpty()) {
			for (String key : params.keySet()) {
				qr.setParameter(key, params.get(key));
			}
		}

		List<T> list = qr.list();
		if (list != null && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	public T get(Class<T> c, Serializable id) {
		Session session = this.sessionFactory.getCurrentSession();
		return (T) session.get(c, id);
	}

	@Override
	public T get(String hql) {
		Query qr = this.sessionFactory.getCurrentSession().createQuery(hql);
		List<T> list = qr.list();
		if (list != null && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public List<T> find(String hql, Map<String, Object> params) {
		Query qr = this.sessionFactory.getCurrentSession().createQuery(hql);
		if (params != null && !params.isEmpty()) {
			for (String key : params.keySet()) {
				qr.setParameter(key, params.get(key));
			}
		}
		return qr.list();
	}

	@Override
	public void delete(T entity) {
		Session session = this.sessionFactory.getCurrentSession();
		session.delete(entity);
		session.flush();
	}

	@Override
	public void update(T entity) {
		Session session = this.sessionFactory.getCurrentSession();
		session.update(entity);
		session.flush();
	}

	

}
